package com.hqyj.service.shiro.realm;

import com.hqyj.pojo.TbEstateManager;
import com.hqyj.service.TbEstateManagerService;
import com.hqyj.service.shiro.ShiroUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * ShiroRealm，实现用户数据的访问
 * @Author franxhao
 */
@Component("shiroRealm")
public class ShiroAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    TbEstateManagerService estateManagerService;

    /**
     * 身份授权认证
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        ShiroUser shiroUser = (ShiroUser) principalCollection.getPrimaryPrincipal();
        String username = shiroUser.getUsername();
        //estateManagerService.getPermissions(username);
        return null;
    }

    /**
     * 身份认证信息
     * 重写该方法，从数据库中获取注册用户和对应的密码，封装成 AuthenticationInfo 对象返回
     * @param token 当前登录用户的身份标识
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 已知用户名
        String loginName = token.getPrincipal().toString();

        // 再根据用户名从数据库中找密码
        TbEstateManager manager = estateManagerService.getByLoginName(loginName);
        // 无此用户抛出异常，有则获取密码
        if (manager == null) {
            throw  new AccountException("The account do not exist.");
        }
        String password = manager.getPassword();

        // 用 AuthenticationInfo 对象，封装 loginName 和 password
        ShiroUser shiroUser = new ShiroUser();
        shiroUser.setId(manager.getId());
        shiroUser.setUsername(manager.getLoginName());
        shiroUser.setPassword(manager.getPassword());
        shiroUser.setAuthCacheKey(manager.getLoginName() + manager.getId());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(shiroUser, password, this.getName());
        return info;
    }
}
